<template>
  <div class="flash-sale-admin">
    <el-card class="admin-header">
      <div class="header-content">
        <h1>秒杀活动管理</h1>
        <div class="header-actions">
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            创建活动
          </el-button>
          <el-button type="success" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon active">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.activeActivities }}</div>
              <div class="stat-label">进行中活动</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon products">
              <el-icon><Box /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalProducts }}</div>
              <div class="stat-label">秒杀商品</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon orders">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.todayOrders }}</div>
              <div class="stat-label">今日订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon revenue">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ statistics.todayRevenue }}</div>
              <div class="stat-label">今日收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 活动管理表格 -->
    <el-card class="activities-table">
      <template #header>
        <div class="card-header">
          <h3>秒杀活动列表</h3>
          <div class="table-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索活动名称"
              style="width: 200px"
              @input="searchActivities"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="statusFilter" placeholder="状态筛选" @change="filterActivities">
              <el-option label="全部" value="" />
              <el-option label="未开始" value="0" />
              <el-option label="进行中" value="1" />
              <el-option label="已结束" value="2" />
              <el-option label="已取消" value="3" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table :data="filteredActivities" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="活动名称" min-width="150" />
        <el-table-column prop="description" label="活动描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalStock" label="总库存" width="100" />
        <el-table-column prop="soldCount" label="已售" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewActivity(scope.row)">
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="editActivity(scope.row)"
              :disabled="scope.row.status === 1"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteActivity(scope.row)"
              :disabled="scope.row.status === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchActivities"
          @current-change="fetchActivities"
        />
      </div>
    </el-card>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      :title="editingActivity ? '编辑活动' : '创建活动'" 
      width="600px"
      @close="resetForm"
    >
      <el-form :model="activityForm" :rules="activityRules" ref="activityFormRef" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input 
            v-model="activityForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入活动描述" 
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="activityForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitActivity" :loading="submitting">
            {{ editingActivity ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 活动详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="活动详情" width="80%" top="5vh">
      <div class="activity-detail" v-if="selectedActivity">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="活动ID">{{ selectedActivity.id }}</el-descriptions-item>
          <el-descriptions-item label="活动名称">{{ selectedActivity.name }}</el-descriptions-item>
          <el-descriptions-item label="活动描述" :span="2">{{ selectedActivity.description }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(selectedActivity.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(selectedActivity.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedActivity.status)">
              {{ getStatusText(selectedActivity.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总库存">{{ selectedActivity.totalStock }}</el-descriptions-item>
          <el-descriptions-item label="已售数量">{{ selectedActivity.soldCount }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(selectedActivity.createTime) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 商品列表 -->
        <div class="activity-products">
          <div class="products-header">
            <h4>秒杀商品列表</h4>
            <el-button type="primary" size="small" @click="showAddProductDialog = true">
              <el-icon><Plus /></el-icon>
              添加商品
            </el-button>
          </div>
          
          <el-table :data="activityProducts" stripe>
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="originalPrice" label="原价" width="100">
              <template #default="scope">
                ¥{{ scope.row.originalPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="flashPrice" label="秒杀价" width="100">
              <template #default="scope">
                ¥{{ scope.row.flashPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="80" />
            <el-table-column prop="soldCount" label="已售" width="80" />
            <el-table-column prop="limitPerUser" label="限购" width="80" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="warning" size="small" @click="editProduct(scope.row)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="deleteProduct(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Refresh, TrendCharts, Box, Document, Money, Search,
  Edit, Delete, View 
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const showAddProductDialog = ref(false)
const editingActivity = ref(null)
const selectedActivity = ref(null)

// 搜索和筛选
const searchKeyword = ref('')
const statusFilter = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 活动列表
const activities = ref([])
const activityProducts = ref([])

// 统计数据
const statistics = ref({
  activeActivities: 0,
  totalProducts: 0,
  todayOrders: 0,
  todayRevenue: 0
})

// 活动表单
const activityForm = reactive({
  name: '',
  description: '',
  startTime: '',
  endTime: ''
})

// 表单验证规则
const activityRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

const activityFormRef = ref()

// 计算属性 - 过滤后的活动列表
const filteredActivities = computed(() => {
  let filtered = activities.value

  if (searchKeyword.value) {
    filtered = filtered.filter(activity =>
      activity.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  if (statusFilter.value !== '') {
    filtered = filtered.filter(activity =>
      activity.status.toString() === statusFilter.value
    )
  }

  return filtered
})

// 方法定义
// 获取活动列表
const fetchActivities = async () => {
  loading.value = true
  try {
    const res = await request.get('/flash-sale/admin/list', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (res && res.data) {
      activities.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const res = await request.get('/flash-sale/admin/statistics')
    if (res && res.data) {
      statistics.value = res.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 刷新数据
const refreshData = () => {
  fetchActivities()
  fetchStatistics()
}

// 搜索活动
const searchActivities = () => {
  // 搜索逻辑已在计算属性中实现
}

// 筛选活动
const filterActivities = () => {
  // 筛选逻辑已在计算属性中实现
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 未开始
    case 1: return 'success'  // 进行中
    case 2: return 'info'     // 已结束
    case 3: return 'danger'   // 已取消
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已结束'
    case 3: return '已取消'
    default: return '未知'
  }
}

// 查看活动详情
const viewActivity = async (activity) => {
  selectedActivity.value = activity
  showDetailDialog.value = true

  // 获取活动商品列表
  try {
    const res = await request.get(`/flash-sale/products/${activity.id}`)
    if (res && res.data) {
      activityProducts.value = res.data
    }
  } catch (error) {
    console.error('获取活动商品失败:', error)
    ElMessage.error('获取活动商品失败')
  }
}

// 编辑活动
const editActivity = (activity) => {
  editingActivity.value = activity
  activityForm.name = activity.name
  activityForm.description = activity.description
  activityForm.startTime = new Date(activity.startTime)
  activityForm.endTime = new Date(activity.endTime)
  showCreateDialog.value = true
}

// 删除活动
const deleteActivity = (activity) => {
  ElMessageBox.confirm(
    `确定要删除活动"${activity.name}"吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await request.delete(`/flash-sale/admin/delete/${activity.id}`)
      ElMessage.success('删除成功')
      fetchActivities()
    } catch (error) {
      console.error('删除活动失败:', error)
      ElMessage.error('删除活动失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交活动表单
const submitActivity = async () => {
  if (!activityFormRef.value) return

  await activityFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const data = {
          name: activityForm.name,
          description: activityForm.description,
          startTime: activityForm.startTime,
          endTime: activityForm.endTime
        }

        if (editingActivity.value) {
          // 更新活动
          data.id = editingActivity.value.id
          await request.put('/flash-sale/admin/update', data)
          ElMessage.success('更新成功')
        } else {
          // 创建活动
          await request.post('/flash-sale/admin/add', data)
          ElMessage.success('创建成功')
        }

        showCreateDialog.value = false
        fetchActivities()
      } catch (error) {
        console.error('提交活动失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  editingActivity.value = null
  activityForm.name = ''
  activityForm.description = ''
  activityForm.startTime = ''
  activityForm.endTime = ''
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
}

// 编辑商品
const editProduct = (product) => {
  ElMessage.info('编辑商品功能开发中...')
}

// 删除商品
const deleteProduct = (product) => {
  ElMessageBox.confirm(
    `确定要删除商品"${product.productName}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await request.delete(`/flash-sale/admin/product/delete/${product.id}`)
      ElMessage.success('删除成功')
      viewActivity(selectedActivity.value) // 刷新商品列表
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchActivities()
  fetchStatistics()
})
</script>

<style scoped>
.flash-sale-admin {
  padding: 20px;
}

.admin-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.products {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.activities-table {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.activity-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.activity-products {
  margin-top: 20px;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.products-header h4 {
  margin: 0;
}
</style>
